package com.tfswue.nyf.exception;

import com.tfswue.nyf.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * @author daygods
 * @date 2025-07-10
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Map<String, Object> handleBusinessException(BusinessException e, HttpServletRequest request) {
        logger.warn("业务异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());
        return ResponseUtil.error(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String, Object> handleValidationException(MethodArgumentNotValidException e) {
        String errorMessage = e.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        logger.warn("参数校验异常: {}", errorMessage);
        return ResponseUtil.error("400", "参数校验失败: " + errorMessage);
    }
    
    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Map<String, Object> handleBindException(BindException e) {
        String errorMessage = e.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        logger.warn("绑定异常: {}", errorMessage);
        return ResponseUtil.error("400", "参数绑定失败: " + errorMessage);
    }
    
    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Map<String, Object> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        logger.warn("非法参数异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());
        return ResponseUtil.error("400", "参数错误: " + e.getMessage());
    }
    
    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public Map<String, Object> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        logger.error("空指针异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI(), e);
        return ResponseUtil.error("500", "系统内部错误");
    }
    
    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public Map<String, Object> handleException(Exception e, HttpServletRequest request) {
        logger.error("系统异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI(), e);
        return ResponseUtil.error("500", "系统内部错误");
    }
}

/**
 * 业务异常类
 */
class BusinessException extends RuntimeException {
    private String code;
    
    public BusinessException(String message) {
        super(message);
        this.code = "500";
    }
    
    public BusinessException(String code, String message) {
        super(message);
        this.code = code;
    }
    
    public String getCode() {
        return code;
    }
}